<script setup>
import { getOrderAPI, createOrderAPI } from "@/apis/order";
import { onMounted, ref,computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useCarStore } from "@/stores/car";
import { userInfoStore } from "@/stores/user";
import { ElMessage } from "element-plus";
import { formatDate } from "@/utils/common";
import { getUserAddressAPI } from "@/apis/user";

const carStore = useCarStore();
const router = useRouter();
const route = useRoute();

const way = ref(0);
const optionsWay = [
  { label: "自提", value: 0 },
  { label: "快递配送", value: 1 },
];
const cartIds = route.query.cartIds ? JSON.parse(route.query.cartIds) : [];
const sellerId = JSON.parse(route.query.sellerId || []);
const deliveryTime = ref(""); // 自提时间
const checkInfo = ref([]); // 订单对象
const addressData = ref([]);
const curAddress = ref({
  address: "",
}); // 地址对象
const postFee = ref(0);
const totalPayPrice = ref(0);
const disabledDate = (date) => {
      return date < new Date()
}

const getUserAddress = async () => {
  let res = await getUserAddressAPI(userInfoStore().userInfo.userId);
  // console.log("获取地址: ",addressData);
  addressData.value = res.data.data;
  console.log("获取地址: ",addressData.value);
  addressData.value.map((item) => {

    return (item.addressStatus = item.addressStatus === 2 ? "默认地址" : "普通地址");
  });

  curAddress.value = addressData.value.find((item) => item.addressStatus === "默认地址");
  console.log("curAddress.value1: ", curAddress.value);
  if(curAddress.value == undefined && addressData.value != null)
  {
    curAddress.value = addressData.value[0];
  }
  console.log("curAddress.value2: ", curAddress.value);
};

const getOrderList = async () => {
  //   let res = await getOrderAPI();
  console.log("router.query: ", route.query);
  if (route.query.productId) {
    checkInfo.value = [route.query];
  } else {
    checkInfo.value = carStore.cartSelectList;
  }
  console.log("carStore.cartSelectList: ", carStore.cartSelectList);
  console.log("checkInfo", checkInfo.value);
  await getUserAddress();
  totalPayPrice.value = carStore.selectedPrice + postFee.value;
};
onMounted(() => getOrderList());
//控制切换地址弹窗显示
const showDialog = ref(false);

const activeAddress = ref({});

const open = () => {
  showDialog.value = true;
  activeAddress.value = curAddress.value;
  console.log("addressData.value:"+addressData.value)
};

const switchAddress = (item) => {
  activeAddress.value = item;
  console.log("activeAddress.value:"+activeAddress.value)
};
const confirm = () => {
  curAddress.value = activeAddress.value;
  showDialog.value = false;
};

const submitOrder = async () => {
  if (way.value === 0) {
    if (!deliveryTime.value) {
      ElMessage.warning("请先选择自提时间");
      return;
    }
  } else {
    if (!curAddress.value) {
      ElMessage.warning("请先选择快递地址");
      return;
    }
  }
  console.log("curAddress:"+curAddress.value)
  const orderDate = {
    uid: userInfoStore().userInfo.userId,
    // sellerId: sellerId,
    deliveryMethod: way.value,

    deliveryAddress: way.value ===1 ? curAddress.value.address : null,
    deliveryTime: way.value === 0 && deliveryTime.value ? formatDate(deliveryTime.value) : null,
    orderImList: route.query.productId
      ? checkInfo.value.map((item) => {
          return {
            productId: item.productId,
            quantity: item.count,
            price: item.price,
          };
        })
      : checkInfo.value.map((item) => {
          return {
            productId: item.productInfo.products.productId,
            quantity: item.count,
            price: item.productInfo.products.price,
          };
        }),
    totalAmount: route.query.productId
      ? checkInfo.value.reduce((total, item) => {
          return total + item.price * item.count;
        }, 0)
      : checkInfo.value.reduce((total, item) => {
          return total + item.productInfo.products.price * item.count;
        }, 0),
        cartIds: cartIds,
  }
  let res = await createOrderAPI(orderDate);
  console.log("createOrderAPI", res);
  ElMessage.success("订单创建成功");
  // 清空已购买的商品
  carStore.clearSelectedItems()
  // 如果需要，可以更新购物车列表
  await carStore.updateCarList()
  await router.push({
    path: "/pay",
    query: {
      ...res.data,
    },
  });
};

//计算金额明细
const calculateTotal = computed(() => {
  if (route.query.productId) {
    // 直接购买单个商品的情况
    return {
      count: Number(route.query.count),
      total: Number(route.query.price) * Number(route.query.count)
    }
  } else {
    // 购物车多商品情况
    return carStore.cartSelectList.reduce((acc, item) => {
      const price = item?.productInfo?.products?.price || 0
      const count = item.count || 1
      return {
        count: acc.count + count,
        total: acc.total + (price * count)
      }
    }, { count: 0, total: 0 })
  }
})
</script>

<template>
  <div class="xtx-pay-checkout-page">
    <div class="container">
      <div class="wrapper">
        <el-segmented v-model="way" :options="optionsWay" size="large" />
        <!-- 配送时间 -->
        <div v-if="way === 0">
          <h3 class="box-title">自提时间</h3>

          <div class="box-body">
            <el-date-picker
              v-model="deliveryTime"
              type="date"
              placeholder="请选择自提时间"
              size="large"
              :disabled-date="disabledDate"
            />
          </div>
        </div>
        <!-- 收货地址 -->
        <div v-if="way === 1">
          <h3 class="box-title">收货地址</h3>
          <div class="box-body">
            <div class="address">
              <div class="text">
                <div class="none" v-if="!curAddress">
                  您需要先添加收货地址才可提交订单。
                </div>
                <ul v-else>
                  <li>
                    <span>收<i />货<i />人：</span>{{ curAddress.name }}
                  </li>
                  <li><span>联系方式：</span>{{ curAddress.phone }}</li>
                  <li>
                    <span>收货地址：</span>
                    {{ curAddress.address }}
                  </li>
                </ul>
              </div>
              <div class="action">
                <el-button size="large" @click="open" v-if="curAddress">切换地址</el-button>
                <el-button size="large" @click="router.push('/member/address')"
                  >添加地址</el-button
                >
              </div>
            </div>
          </div>
        </div>
        <!-- 商品信息 -->
        <h3 class="box-title">商品信息</h3>
        <div class="box-body" v-if="route.query.productId">
          <table class="goods">
            <thead>
              <tr>
                <th width="520">商品信息</th>
                <th width="170">单价</th>
                <th width="170">数量</th>
                <th width="170">小计</th>
                <th width="170">实付</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="i in checkInfo" :key="i.id">
                <td>
                  <a href="javascript:;" class="info">
                    <img :src="i.imageUrl" alt="" />
                    <div class="right">
                      <p>{{ i.title }}</p>
                      <p>{{ i.description }}</p>
                    </div>
                  </a>
                </td>
                <td>&yen;{{ i.price }}</td>
                <td>{{ i.count }}</td>
                <td>&yen;{{ (i.price * i.count).toFixed(2) }}</td>
                <td>&yen;{{ (i.price * i.count).toFixed(2) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="box-body" v-else>
          <table class="goods">
            <thead>
              <tr>
                <th width="520">商品信息</th>
                <th width="170">单价</th>
                <th width="170">数量</th>
                <th width="170">小计</th>
                <th width="170">实付</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="i in carStore.cartSelectList"
                :key="i?.productInfo?.productImages[0].productId"
              >
                <td>
                  <a href="javascript:;" class="info">
                    <RouterLink :to="`/detail/${i.productInfo.products.productId}`">
                      <img :src="i?.productInfo?.productImages[0]?.imageUrl" alt="" />
                    </RouterLink>
                    <div class="right">
                      <p>
                        {{ i?.productInfo?.products?.title }}
                      </p>
                      <p>
                        {{ i?.productInfo?.products?.description }}
                      </p>
                    </div>
                  </a>
                </td>
                <td>&yen;{{ i?.productInfo?.products?.price }}</td>
                <td>{{ i?.count }}</td>
                <td>&yen;{{ (i?.productInfo?.products?.price * i.count).toFixed(2) }}</td>
                <td>&yen;{{ (i?.productInfo?.products?.price * i.count).toFixed(2) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <!-- 金额明细 -->
        <h3 class="box-title">金额明细</h3>
        <div class="box-body" v-if="route.query.productId">
          <div class="total">
            <dl>
              <dt>商品件数：</dt>
              <!-- carStore.selectedCount || -->
              <dd>{{ calculateTotal.count }}件</dd>
            </dl>
            <dl>
              <dt>商品总价：</dt>
              <dd>
                <!--  carStore.selectedPrice.toFixed(2) || -->
                ¥{{ calculateTotal.total.toFixed(2) }}
              </dd>
            </dl>
            <!-- <dl>
              <dt>运<i></i>费：</dt>
              <dd>¥{{ postFee?.toFixed(2) }}</dd>
            </dl> -->
            <dl>
              <dt>应付总额：</dt>
              <!-- totalPayPrice?.toFixed(2) -->
              <dd class="price">{{ calculateTotal.total.toFixed(2) }}</dd>
            </dl>
          </div>
        </div>

        <div class="box-body" v-else>
          <div class="total">
            <dl>
              <dt>商品件数：</dt>
              <dd>{{ calculateTotal.count }}件</dd>
            </dl>
            <dl>
              <dt>商品总价：</dt>
              <dd>¥{{ calculateTotal.total.toFixed(2) }}</dd>
            </dl>
            <!-- <dl>
              <dt>运<i></i>费：</dt>
              <dd>¥{{ postFee?.toFixed(2) }}</dd>
            </dl> -->
            <dl>
              <dt>应付总额：</dt>
              <dd class="price">{{ calculateTotal.total.toFixed(2) }}</dd>
            </dl>
          </div>
        </div>

        <!-- 提交订单 -->
        <div class="submit">
          <el-button type="primary" size="large" @click="submitOrder">提交订单</el-button>
        </div>
      </div>
    </div>
  </div>
  <!-- 切换地址 -->
  <el-dialog v-model="showDialog" title="切换收货地址" width="30%" center>
    <div class="addressWrapper">
      <div
        class="text item"
        :class="{ active: activeAddress.addressId === item.addressId }"
        v-for="item in addressData"
        :key="item.addressId"
        @click="switchAddress(item)"
      >
        <ul>
          <li>
            <span>收<i />货<i />人：</span>{{ item.name }}
          </li>
          <li><span>联系方式：</span>{{ item.phone }}</li>
          <li><span>收货地址：</span>{{ item.address }}</li>
        </ul>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.xtx-pay-checkout-page {
  margin-top: 20px;

  .wrapper {
    background: #fff;
    padding: 0 20px;

    .box-title {
      font-size: 16px;
      font-weight: normal;
      padding-left: 10px;
      line-height: 70px;
      border-bottom: 1px solid #f5f5f5;
    }

    .box-body {
      padding: 20px 0;
    }
  }
}

.address {
  border: 1px solid #f5f5f5;
  display: flex;
  align-items: center;

  .text {
    flex: 1;
    min-height: 90px;
    display: flex;
    align-items: center;

    .none {
      line-height: 90px;
      color: #999;
      text-align: center;
      width: 100%;
    }

    > ul {
      flex: 1;
      padding: 20px;

      li {
        line-height: 30px;

        span {
          color: #999;
          margin-right: 5px;

          > i {
            width: 0.5em;
            display: inline-block;
          }
        }
      }
    }

    > a {
      color: $xtxColor;
      width: 160px;
      text-align: center;
      height: 90px;
      line-height: 90px;
      border-right: 1px solid #f5f5f5;
    }
  }

  .action {
    width: 420px;
    text-align: center;

    .btn {
      width: 140px;
      height: 46px;
      line-height: 44px;
      font-size: 14px;

      &:first-child {
        margin-right: 10px;
      }
    }
  }
}

.goods {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;

  .info {
    display: flex;
    text-align: left;

    img {
      width: 70px;
      height: 70px;
      margin-right: 20px;
    }

    .right {
      line-height: 24px;

      p {
        &:last-child {
          color: #999;
        }
      }
    }
  }

  tr {
    th {
      background: #f5f5f5;
      font-weight: normal;
    }

    td,
    th {
      text-align: center;
      padding: 20px;
      border-bottom: 1px solid #f5f5f5;

      &:first-child {
        border-left: 1px solid #f5f5f5;
      }

      &:last-child {
        border-right: 1px solid #f5f5f5;
      }
    }
  }
}

.my-btn {
  width: 228px;
  height: 50px;
  border: 1px solid #e4e4e4;
  text-align: center;
  line-height: 48px;
  margin-right: 25px;
  color: #666666;
  display: inline-block;

  &.active,
  &:hover {
    border-color: $xtxColor;
  }
}

.total {
  dl {
    display: flex;
    justify-content: flex-end;
    line-height: 50px;

    dt {
      i {
        display: inline-block;
        width: 2em;
      }
    }

    dd {
      width: 240px;
      text-align: right;
      padding-right: 70px;

      &.price {
        font-size: 20px;
        color: $priceColor;
      }
    }
  }
}

.submit {
  text-align: right;
  padding: 60px;
  border-top: 1px solid #f5f5f5;
}

.addressWrapper {
  max-height: 500px;
  overflow-y: auto;

  .text.item {
    border: 1px solid #e4e4e4;
    margin-bottom: 10px;
    border-radius: 4px;
    padding: 10px;
    cursor: pointer;
    transition: all 0.3s ease; // 添加过渡效果

    // 悬停状态
    &:hover {
      border-color: #c0c4cc;
      background-color: #f5f7fa;
      transform: translateY(-2px); // 轻微上浮效果
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    // 选中状态（保持比悬停更明显的样式）
    &.active {
      border: 1px solid var(--el-color-primary);
      background-color: rgba(64, 158, 255, 0.08);
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }

    // 同时选中和悬停的状态
    &.active:hover {
      background-color: rgba(64, 158, 255, 0.12);
    }

    ul {
      margin: 0;
      padding: 0;
      list-style: none;

      li {
        line-height: 1.8;
        span {
          color: #666;
          margin-right: 5px;
        }
      }
    }
  }
}
</style>
@/stores/car1
